<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
namespace Shop\Controller;

use Shop\Api\CategoryApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\ShoppingCartApi;
use Shop\Api\StoreApi;

class ShoppingCartController extends ShopController{

	protected function _initialize(){
		parent::_initialize();

	}
	
	
	/**
	 * 购物车查看页面
	 */
	public function index(){
		session("confirm_order_info",null);

        if(!empty($this->userinfo)){

            $map = array(
                'uid'=>$this->userinfo['uid'],
            );

            $result = apiCall(ShoppingCartApi::QUERY_NO_PAGING,array($map));

            if($result['status']){
                $this->assign("cart",$result['info']);
            }

            if(empty($result['info'])){
                //如果空了，则清除购物车数目缓存
                $this->clearCartItemCache();
            }

        }else{
            $this->assign("cart",false);
        }
		$this->theme($this->themeType)->display();
	}

	/**
	 * 从购物车中移除一项物品
	 */
	public function delItem(){
		$id = $this->_get("id",0,"缺失参数!");

        $map = array(
            'id'=>$id,
        );
        $result = apiCall(ShoppingCartApi::DELETE,array($map));
        if($result['status']){
            $this->clearCartItemCache();
			$this->success("删除成功！");
		}else{
			$this->error("删除失败！");
		}
		
	}

    /**
     * 立即购买
     * TODO: 现在是做中转通过购物车实现
     * @author hebiduhebi@126.com
     */
    public function buy(){
        $this->addItem(true);
    }
	
	/**
	 * 加入商品到购物车之中
     * POST:
     * pid,item_count,psku_id,sku_desc 4个参数
     * @author hebiduhebi@126.com
	 */
	public function addItem($is_buy=false){

        if(empty($this->userinfo)){
            $this->error("请先登录!",U('Shop/Index/login'));
        }


		$id = $this->_get("pid",0,'缺失商品ID');//缺失商品ID
        $count = $this->_post("item_count",1);//默认一件
        $psku_id = $this->_post("psku_id",'');//默认一件
        $sku_desc = $this->_post("sku_desc",'');//默认一件

		if($count <= 0){
			$this->error("商品数量不对！");
		}
		
		if($id > 0){
			
			$result = apiCall(ProductApi::GET_INFO, array(array('id'=>$id)));
			
			if(!$result['status']){
				LogRecord($result['info'], __FILE__.__LINE__);
				$this->error($result['info']);
			}
			if(is_null($result['info'])){
				$this->error("商品信息获取失败！");
			}

			$product = $result['info'];

			$result = apiCall(ProductSkuApi::GET_INFO, array(array('id'=>$psku_id)));
			
			if(!$result['status']){
				$this->error($result['info']);
			}

			$sku = $result['info'];


            if($product['has_sku'] == 1 && empty($psku_id)){
                $this->error("请先选择规格!");
            }

            $result = false;
			if($product['has_sku'] == 0){

				$result = $this->addToCart($product,false,$count);
				
			}elseif($product['has_sku'] == 1 && is_array($sku)){
				
				if(is_null($sku)){
					$this->error("商品规格信息获取失败！");
				}

                $sku['sku_desc'] = $sku_desc;
				//多规格
                $result = $this->addToCart($product,$sku,$count);
			}else{
				$this->error("操作失败！");
			}

            if(is_array($result) && $result['status']){
                $cart_id = $result['info'];
                if($is_buy){
                    $this->success("正在跳转～",U('Shop/Orders/checkout',array('cart_id'=>$cart_id,'direct'=>1)));
                }else{
                    $this->success("成功添加到购物车！");
                }
            }

		}else{
			$this->error("参数错误");
		}
		
	}

    /**
     * 商品id，商品名称，商品图片（默认主图），商品数量count，是否多规格，商品价格，商品原价，
     * 运费,
     * @param $product
     * @param $sku
     * @param $count
     * @return array|mixed
     */
	private function addToCart($product,$sku,$count){

        $result = apiCall(CategoryApi::GET_INFO,array(array('code'=>$product['dt_tariff_code'])));
        $taxRate = 0;
        if($result['status'] && is_array($result['info'])){
            $taxRate = $result['info']['taxrate'];
        }
		$item = array(
            'uid'=>$this->userinfo['uid'],
			'p_id'=>$product['id'],
			'icon_url'=>$product['main_img'],//商品图片
			'count'=>$count, // 商品数量
			'name'=>$product['name'],
			'has_sku'=>$product['has_sku'],
			'sku_desc'=>'',
			'sku_id'=>'',
			'store_id'=>$product['store_id'],
			'express'=>0,
            'weight'=>$product['weight'],
            'taxrate'=>$taxRate,
            'template_id'=>$product['template_id'],
		);

		if($sku === false){
			//统一规格下
			$item['price'] = $product['price'];
			$item['ori_price'] = $product['ori_price'];
		}else{
            $item['sku_id'] = $sku['sku_id'];
            $item['psku_id'] = $sku['id'];
			$item['price'] = $sku['price'];
			$item['ori_price'] = $sku['ori_price'];
			$item['sku_desc'] = $sku['sku_desc'];
			if(!empty($sku['icon_url'])){
				$item['icon_url'] = $sku['icon_url'];//商品图片
			}
		}

        $map = array(
            'uid'=>$this->userinfo['uid'],
            'p_id'=>$item['p_id'],
        );

        if($item['has_sku']){
            $map['psku_id'] = $item['psku_id'];
        }

        $result = apiCall(ShoppingCartApi::GET_INFO,array($map));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
            return array('status'=>false,'info'=>"参数错误!");
        }

        $cart_id = 0;
        if(is_array($result['info'])){
            $entity = array(
                'count'=>($result['info']['count'] + $item['count']),
    			'icon_url'=>$item['icon_url'],//商品图片
    			'name'=>$item['name'],
            );
            $cart_id = $result['info']['id'];
            $result = apiCall(ShoppingCartApi::SAVE,array($map,$entity));

        }else{
            $result = apiCall(ShoppingCartApi::ADD,array($item));
            if($result['status']){
                $cart_id = $result['info'];
            }
        }

        $this->checkApiCallResult($result);
        $this->clearCartItemCache();
        if($cart_id == 0){
            return array('status'=>false,'info'=>0);
	    }else{
            return array('status'=>true,'info'=>$cart_id);
        }
    }


}

